package com.zitangkou.gateway.config;

import com.google.gson.Gson;
import com.zitangkou.common.enums.RespEnum;
import com.zitangkou.common.global.GlobalException;
import com.zitangkou.common.global.UserContent;
import com.zitangkou.gateway.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.util.PathMatcher;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class WebFluxAuthenticationManager implements ReactiveAuthenticationManager {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private Gson gson;

    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        try {
            String token = authentication.getCredentials().toString();
            // token 为空，没有权限
            if (StringUtils.isNotBlank(token)) {
                // 验证 token
                String userInfo = jwtUtil.validateToken(token);
                UserContent user;
                try {
                    user = gson.fromJson(userInfo, UserContent.class);
                } catch (Exception e) {
                    throw new GlobalException(RespEnum.TOKEN_IS_NULL);
                }
                if (null == user) {
                    throw new GlobalException(RespEnum.TOKEN_IS_NULL);
                }
                List<GrantedAuthority> authorities = new ArrayList<>();
                authorities.add(new SimpleGrantedAuthority(user.getUserAccount()));
                return Mono.just(new UsernamePasswordAuthenticationToken(authentication, null, authorities));
            } else {
                return Mono.empty();
            }
        } catch (Exception e) {
            return Mono.empty();
        }
    }
}
